<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
require('echarts/theme/macarons')
import resize from '@/mixins/resize'

import { lineColor, links, nodes } from '../config/scatter'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'scatter'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        grid: {
          left: 5,
          right: 5,
          bottom: 50
        },
        xAxis: {
          type: 'category',
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            rotate: 90
          },
          data: nodes.map(function (node) {
            return node.name
          })
        },
        yAxis: {
          show: false
        },

        series: [
          {
            type: 'scatter',
            data: nodes.map(function (node) {
              return {
                value: 0,
                symbolSize: node.symbolSize
              }
            })
          },
          {
            type: 'custom',
            dimension: [
              {
                type: 'ordinal',
                name: 'source'
              },
              {
                // This dumb value will be used in yAxis.
                type: 'number',
                name: 'dumb'
              },
              {
                type: 'ordinal',
                name: 'target'
              }
            ],
            data: links.map(function (link) {
              return [link.source, 0, link.target]
            }),
            renderItem: function (_params, api) {
              const coord0 = api.coord([api.value(0), 0])
              const coord1 = api.coord([api.value(2), 0])
              const cx = (coord0[0] + coord1[0]) / 2
              const r = (coord1[0] - coord0[0]) / 2

              return {
                type: 'arc',
                style: {
                  stroke: lineColor,
                  fill: 'none',
                  opacity: 0.2
                },
                shape: {
                  cx: cx,
                  cy: coord0[1],
                  r: r,
                  startAngle: 0,
                  endAngle: Math.PI,
                  clockwise: false
                }
              }
            }
          }
        ]
      })
    }
  }
}
</script>
